package org.microframework.cloud.logs.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.microframework.base.core.web.page.PageQuery;
import org.microframework.cloud.logs.model.domain.OperationLog;
import org.microframework.cloud.logs.service.IOperationLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 操作日志服务实现类
 * 
 * @author zs
 * @version 1.0.0
 * @date 2024-05-21
 */
@Service
public class OperationLogServiceImpl implements IOperationLogService {

    private static final Logger log = LoggerFactory.getLogger(OperationLogServiceImpl.class);

    /**
     * 记录操作日志
     */
    @Async
    @Override
    public boolean insertOperationLog(OperationLog operLog) {
        try {
            if (operLog == null) {
                return false;
            }
            
            // 设置基本信息
            if (!StringUtils.hasText(operLog.getId())) {
                operLog.setId(UUID.randomUUID().toString());
            }
            if (operLog.getOperTime() == null) {
                operLog.setOperTime(new Date());
            }
            if (operLog.getCreateTime() == null) {
                operLog.setCreateTime(new Date());
            }
            
            return operLog.save();
        } catch (Exception e) {
            log.error("记录操作日志异常", e);
            return false;
        }
    }

    /**
     * 查询操作日志列表
     */
    @Override
    public Page<OperationLog> selectOperationLogList(OperationLog operLog, PageQuery<OperationLog> pageRequest) {
        try {
            StringBuilder sqlBuilder = new StringBuilder("FROM " + OperationLog.TABLE_NAME + " WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (operLog != null) {
                // 构建查询条件
                if (StringUtils.hasText(operLog.getTitle())) {
                    sqlBuilder.append(" AND title LIKE ?");
                    params.add("%" + operLog.getTitle() + "%");
                }
                
                if (StringUtils.hasText(operLog.getOperName())) {
                    sqlBuilder.append(" AND oper_name LIKE ?");
                    params.add("%" + operLog.getOperName() + "%");
                }
                
                if (operLog.getBusinessType() != null) {
                    sqlBuilder.append(" AND business_type = ?");
                    params.add(operLog.getBusinessType());
                }
                
                if (operLog.getStatus() != null) {
                    sqlBuilder.append(" AND status = ?");
                    params.add(operLog.getStatus());
                }
            }
            
            // 设置排序
            String orderBy = StringUtils.hasText(pageRequest.getOrderBy()) ? 
                    pageRequest.getOrderBy() : "oper_time";
            String orderDirection = StringUtils.hasText(pageRequest.getOrderDirection()) ? 
                    pageRequest.getOrderDirection() : "desc";
            sqlBuilder.append(" ORDER BY " + orderBy + " " + orderDirection);
            
            // 执行分页查询
            Page<Record> page = Db.paginate(
                    pageRequest.getPageNumber(), 
                    pageRequest.getPageSize(), 
                    "SELECT *", 
                    sqlBuilder.toString(), 
                    params.toArray());
            
            // 转换查询结果
            List<OperationLog> list = new ArrayList<>();
            for (Record record : page.getList()) {
                list.add(new OperationLog().put(record));
            }
            
            return new Page<>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
        } catch (Exception e) {
            log.error("查询操作日志列表异常", e);
            return new Page<>(new ArrayList<>(), 1, 10, 0, 0);
        }
    }

    /**
     * 批量删除操作日志
     */
    @Override
    public int deleteOperationLogByIds(String[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return 0;
            }
            
            StringBuilder sqlBuilder = new StringBuilder("DELETE FROM " + OperationLog.TABLE_NAME + " WHERE id IN (");
            for (int i = 0; i < ids.length; i++) {
                if (i > 0) {
                    sqlBuilder.append(",");
                }
                sqlBuilder.append("?");
            }
            sqlBuilder.append(")");
            
            return Db.update(sqlBuilder.toString(), (Object[]) ids);
        } catch (Exception e) {
            log.error("删除操作日志异常", e);
            return 0;
        }
    }

    /**
     * 查询操作日志详细信息
     */
    @Override
    public OperationLog selectOperationLogById(String id) {
        try {
            if (!StringUtils.hasText(id)) {
                return null;
            }
            return OperationLog.dao.findById(id);
        } catch (Exception e) {
            log.error("查询操作日志详情异常", e);
            return null;
        }
    }

    /**
     * 清空操作日志
     */
    @Override
    public boolean cleanOperationLog() {
        try {
            return Db.update("TRUNCATE TABLE " + OperationLog.TABLE_NAME) > 0;
        } catch (Exception e) {
            log.error("清空操作日志异常", e);
            return false;
        }
    }
} 